console.log('start success');

const Websocket = require('ws');

; ((Ws) => {
    const server = new Ws.Server({ port: 8098 });

    const init = () => {
        bindEvent();
    }

    function bindEvent() {
        server.on('open', handleOpen);
        server.on('close', handleClose);
        server.on('error', handleError);
        server.on('connection', handleConnection);
    }

    function handleOpen() {
        console.log('websocket open');
    }

    function handleClose() {
        console.log('websocket close');
    }

    function handleError(e) {
        console.log('websocket error',e);
    }

    function handleConnection(ws) {
        console.log('websocket connected');
        ws.on('message', handleMessage);
    }

    function handleMessage(msg) {
        const msgString = msg.toString('utf8');
        const msgJSON = JSON.parse(msgString);
        console.log(msgJSON)
        //把answer发给所有用户
        server.clients.forEach((c) => {
            c.send(msgString)
        })
    }

    init();
})(Websocket);